/**
 * Created by ChenYong on 2017-04-12.
 *
 * 资源列表。
 */

$(function () {
    /** 资源名称的 jQuery 对象 */
    var $resourceName = $("#resource_name");
    /** 父资源名称 jQuery 对象 */
    var $parentName = $("#parent_name");
    /** 权限代码 jQuery 对象 */
    var $permissionCode = $("#permission_code");
    /** 资源类型 jQuery 对象 */
    var $resourceType = $("#resource_type");
    /** 开始日期的 jQuery 对象 */
    var $startDate = $("#start_date");
    /** 结束日期的 jQuery 对象 */
    var $endDate = $("#end_date");
    /** 搜索按钮的 jQuery 对象 */
    var $searchBtn = $("#search_btn");
    /** 资源模态框的 jQuery 对象 */
    var $resourceModal = $("#resource_modal");
    /** 资源列表的表格，DataTables 的 API 对象 */
    var resourceTable = null;

    // 选择开始日期
    $startDate.datepicker({
        format: "yyyy-mm-dd",
        language: "zh-CN",
        clearBtn: true,
        autoclose: true,
        todayHighlight: true
    }).on("changeDate", function (e) {
        var startDate = ($.isNull(e.date) ? null : e.date);

        $endDate.datepicker("setStartDate", startDate);
    });

    // 选择结束日期
    $endDate.datepicker({
        format: "yyyy-mm-dd",
        language: "zh-CN",
        clearBtn: true,
        autoclose: true,
        todayHighlight: true
    }).on("changeDate", function (e) {
        var endDate = ($.isNull(e.date) ? null : e.date);

        $startDate.datepicker("setEndDate", endDate);
    });

    // 监听资源类型下拉列表搜索
    $resourceType.change(function () {
        searchData();
    });

    // 点击搜索按钮
    $searchBtn.click(function (e) {
        searchData();
    });

    // 监听资源模态框打开
    $resourceModal.on("shown.bs.modal", function () {
        // 将滚动条滚动到顶部
        $resourceModal.find(".modal-body").scrollTop("0px");
    });

    // 监听资源模态框关闭
    $resourceModal.on("hidden.bs.modal", function () {
        $resourceModal.find(".modal-body").html("");
    });

    // 点击删除
    $(document).on("click", ".delete_btn", function () {
        var $this = $(this);
        var id = $this.data("id");
        var name = $this.data("name");

        $.showConfirmModal({
            msg: "确定删除【{0}】吗？如果它有子资源的话，也将被删除！！！".format(name),
            confirmFn: function () {
                $.myAjax({
                    url: "web/resource/delete.json",
                    modal: true,
                    data: {
                        id: id
                    },
                    successFn: function (data) {
                        searchData();
                    }
                });
            }
        });
    });

    // 展示资源表格
    resourceTable = $("#resource_table").myDataTable({
        url: "web/resource/list.json",
        searchBtn: $searchBtn,
        sScrollY: "450px",
        sScrollX: true,
        sScrollXInner: "100%",
        aaSorting: [[7, "desc"]],
        aLengthMenu: [10, 30, 50, 100],
        aoColumns: [{
            mData: "checkbox",
            sTitle: "<label class='pos-rel' title='全选'><input type='checkbox' class='ace'><span class='lbl'></span></label>",
            sWidth: "50px",
            sClass: "center",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html("<label class='pos-rel'><input type='checkbox' class='ace' data-id='{0}'><span class='lbl'></span></label>".format(rowData.id));
            }
        }, {
            mData: "resourceName",
            sName: "resourceName",
            sTitle: "资源名称",
            sWidth: "250px"
        }, {
            mData: "parentName",
            sName: "parentName",
            sTitle: "父资源名称",
            sWidth: "250px"
        }, {
            mData: "resourceType",
            sName: "resourceType",
            sTitle: "资源类型",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                // 菜单
                if (rowData.resourceType == 1) {
                    $cell.html("<span class='label label-lg label-success'>菜单</span>");

                    // 按钮
                } else if (rowData.resourceType == 2) {
                    $cell.html("<span class='label label-lg label-primary'>按钮</span>");

                    // 数据
                } else if (rowData.resourceType == 3) {
                    $cell.html("<span class='label label-lg label-info'>数据</span>");
                }
            }
        }, {
            mData: "resourceIcon",
            sName: "resourceIcon",
            sTitle: "资源图标",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                if ($.isNotBlank(rowData.resourceIcon)) {
                    $cell.html("<i class='ace-icon {0} c-red bigger-200'></i>".format(rowData.resourceIcon));
                }
            }
        }, {
            mData: "permissionCode",
            sName: "permissionCode",
            sTitle: "权限代码",
            sWidth: "150px"
        }, {
            mData: "resourceUrl",
            sName: "resourceUrl",
            sTitle: "资源URL"
        }, {
            mData: "createTime",
            sName: "createTime",
            sTitle: "<i class='ace-icon iconfont icon-time bigger-110'></i>时间",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html(rowData.createTime.substring(0, 10));
            }
        }, {
            mData: "operator",
            sTitle: "操作",
            sWidth: "100px",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "<div class='hidden-sm hidden-xs action-buttons'></div>",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                // 根资源不能修改、删除
                if (rowData.id != 1) {
                    $cell.find("div.action-buttons").append("<a class='c-orange' title='修改【{0}】' data-toggle='tooltip' data-placement='left' href='{1}web/resource/update.html?id={2}'><i class='ace-icon iconfont icon-pencil bigger-200'></i></a>".format(rowData.resourceName, globalBasePath, rowData.id));

                    $cell.find("div.action-buttons").append("<a class='delete_btn c-red' title='删除【{0}】' data-id='{1}' data-name='{2}' data-toggle='tooltip' data-placement='left' href='javascript:void(0);'><i class='ace-icon iconfont icon-delete bigger-200'></i></a>".format(rowData.resourceName, rowData.id, rowData.resourceName));
                }
            }
        }],
        successFn: function () {
            $("[data-toggle='tooltip']").tooltip();
        }
    });

    /**
     *
     * 搜索数据。
     *
     */
    function searchData() {
        // 资源名称
        if ($.isNotBlank($resourceName.val()) && ($resourceName.val().length > 50)) {
            $.toast({
                top: 5,
                msg: "资源名称的长度不能大于50个字",
                type: "error",
                close: 3000
            });

            return;
        }

        // 父资源名称
        if ($.isNotBlank($parentName.val()) && ($parentName.val().length > 50)) {
            $.toast({
                top: 5,
                msg: "父资源名称的长度不能大于50个字",
                type: "error",
                close: 3000
            });

            return;
        }

        // 权限代码
        if ($.isNotBlank($permissionCode.val()) && ($permissionCode.val().length > 50)) {
            $.toast({
                top: 5,
                msg: "权限代码的长度不能大于50个字符",
                type: "error",
                close: 3000
            });

            return;
        }

        $parentName.val($.trim($parentName.val()));
        $resourceName.val($.trim($resourceName.val()));
        $permissionCode.val($.trim($permissionCode.val()));

        // 搜索开始…
        if ($.isNotNull(resourceTable)) {
            resourceTable.myAjaxData = {
                endDate: $endDate.val(),
                startDate: $startDate.val(),
                parentName: $parentName.val(),
                resourceType: $resourceType.val(),
                resourceName: $resourceName.val(),
                permissionCode: $permissionCode.val()
            };

            // 刷新资源表格（分页重置）
            resourceTable.ajax.reload();
        }
    }
});